package com.yanxu.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/29-2025
 * @Description: 演示 原子数组的使用方法
 */
public class AtomicArrayDemo {
    //定义一个 原子数组，数组的长度是 1000.
    //此时数组中的每一个元素都是具有原子性的。
    private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);

    public static void main(String[] args) throws InterruptedException {
        Thread[] threadsIncrementer = new Thread[100];
        Thread[] threadsDecrementer = new Thread[100];
        //定义自增runnable 任务、 自定自减runnable 任务
        Incrementer incrementerRunnable = new Incrementer(atomicIntegerArray);
        Decrementer decrementerRunnable = new Decrementer(atomicIntegerArray);

        //初始化 自增操作的100个线程
        //初始化 自减操作的100个线程
        for (int i = 0; i < 100; i++) {
            threadsIncrementer[i] = new Thread(incrementerRunnable);
            threadsDecrementer[i] = new Thread(decrementerRunnable);
        }
        //将 100 个线程全部启动起来。
        for (int i = 0; i < 100; i++) {
            threadsIncrementer[i].start();
            threadsDecrementer[i].start();
        }
        for (int i = 0; i < 100; i++) {
            threadsIncrementer[i].join();
            threadsDecrementer[i].join();
        }

        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            int val = atomicIntegerArray.get(i);
            System.out.println(val);
        }
    }
}

class Incrementer implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Incrementer(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndIncrement(i);
        }
    }
}

class Decrementer implements Runnable {
    private AtomicIntegerArray atomicIntegerArray;

    public Decrementer(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndDecrement(i);
        }
    }
}